package com.sgu6.sgu6_machine.util;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.sgu6.middleware.manager.ThreadManager;
import com.sgu6.sgu6_machine.common.Constant;
import com.sgu6.sgu6_machine.config.OssConfig;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;

public class OssUtil {

    private static final String TAG = OssUtil.class.getSimpleName();
    public static OssUtil ossUtil;
    public OSS oss;

    public static OssUtil getInstance(Context context) {
        if (ossUtil == null) {
            ossUtil = new OssUtil(context);
        }
        return ossUtil;
    }


    public OssUtil(Context context) {
        oss = initOss(context);
    }


    private OSS initOss(Context context) {
        OSSCredentialProvider credentialProvider;
        //使用自己的获取STSToken的类
        credentialProvider = new OSSPlainTextAKSKCredentialProvider(OssConfig.OSS_ACCESS_KEY_ID, OssConfig.OSS_ACCESS_KEY_SECRET);

        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        return new OSSClient(context, OssConfig.OSS_ENDPOINT, credentialProvider, conf);
    }

    public void download(String downloadUrl, String savePath, OnImageDownloadListener listener) {
        ThreadManager.getThreadPollProxy().execute(new Runnable() {
            @Override
            public void run() {
                // 构造下载文件请求。 //images/logo/80f23f3121d541dabcc4b78838a10233/logo.png
                GetObjectRequest get = new GetObjectRequest(OssConfig.BUCKET_NAME, downloadUrl);

                OSSAsyncTask task = oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
                    @Override
                    public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                        // 请求成功。
                        Log.d("asyncGetObject", "DownloadSuccess");
                        Log.d("Content-Length", "" + result.getContentLength());
                        listener.onDownloadSuccess();

                        InputStream inputStream = result.getObjectContent();
                        byte[] buffer = new byte[2048];
                        FileOutputStream fos = null;
                        File file = new File(Constant.FILE_ROOT_PATH + savePath, divideSuffixFormUrl(downloadUrl));
                        try {
                            fos = new FileOutputStream(file);
                            int len;
                            while ((len = inputStream.read(buffer)) != -1) {
                                // 您可以在此处编写代码来处理下载的数据。
                                Log.i(TAG, "onSuccess: " + len);
                                fos.write(buffer, 0, len);
                            }
                            fos.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    // GetObject请求成功，将返回GetObjectResult，其持有一个输入流的实例。返回的输入流，请自行处理。
                    public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                        listener.onDownloadFailed();
                        // 请求异常。
                        if (clientExcepion != null) {
                            // 本地异常，如网络异常等。
                            clientExcepion.printStackTrace();
                        }
                        if (serviceException != null) {
                            // 服务异常。
                            Log.e("ErrorCode", serviceException.getErrorCode());
                            Log.e("RequestId", serviceException.getRequestId());
                            Log.e("HostId", serviceException.getHostId());
                            Log.e("RawMessage", serviceException.getRawMessage());
                        }
                    }
                });

// task.cancel(); // 可以取消任务。
                task.waitUntilFinished(); // 等待任务完成。
            }
        });
    }

    public String divideSuffixFormUrl(String url) {
        String[] names = url.split("/");
        return names[names.length - 1];
    }

    public String getURL(String imagePath) {
        //设置图片有效时间
//        String url = oss.presignPublicObjectURL(OssConfig.BUCKET_NAME, imagePath);
        //设置图片有效时间
        Date expiration = new Date(new Date().getTime() + 1000 * 60 * 30);
        String url = null;
        try {
            url = oss.presignConstrainedObjectURL(OssConfig.BUCKET_NAME, imagePath, 1000 * 60 * 30);
            Log.i(TAG, "getURL: ");
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return url;
    }


    public interface OnImageDownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess();

        /**
         * @param progress 下载进度
         */
        void onDownloading(int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed();
    }


}
